package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author wangjian
 * @since 2022-06-26
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
    //先判断用户名密码是否为空
        if(dto !=null|| StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPasswork())){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询用户
        LambdaQueryWrapper<AdUser> queryWrapperName = new LambdaQueryWrapper<>();
        queryWrapperName.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(queryWrapperName);
        //如果查不到结果
        if (one ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //如果查询到 在比较密码
        String password =dto.getPasswork()+one.getSalt();
         password= DigestUtils.md5Hex(password);
        if(!StringUtils.equals(password,one.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Map resultMap = new HashMap<>();
    one.setSalt("");
        one.setPassword("");
        one.setPhone("");
        resultMap.put("user",one);

        Map claimMaps = new HashMap();
        claimMaps.put("name",one.getName());
        String token = AppJwtUtil.getToken(claimMaps);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
